package com.egao.gzh.service;

import com.egao.common.core.damon.baiduword.service.BdWordService;
import com.egao.common.system.entity.User;
import com.egao.common.system.service.UserService;
import com.egao.gzh.entity.reply.*;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Damon
 * @create 2020-08-26 14:33
 */
@Service
public class Wxservice {

    @Autowired
    private UserService userService;
    public Map<String, String> parseRequest(InputStream is) throws IOException, DocumentException {
        Map<String, String> map = new HashMap<>();
        SAXReader reader = new SAXReader();
        //读取输入流,获取文档对象
        Document document = reader.read(is);
        //根据文档对象获取根节点
        Element rootElement = document.getRootElement();
        //获取根节点下的子节点
        List<Element> elements = rootElement.elements();
        for (Element e : elements) {
            map.put(e.getName(), e.getStringValue());
        }
        return map;
    }

    /**
     * 用于处理所有的事件和消息的回复
     * @param requestMap
     * @return
     */
    public String getRespose(Map<String, String> requestMap) {
//        System.out.println(requestMap);
        BaseMessage msg = null;
        String msgType = requestMap.get("MsgType");
        switch (msgType) {
            //处理文本消息
            case "text":
                msg = dealTextMessage(requestMap);
                break;
            case "image":
                msg = dealImage(requestMap);
                break;
            case "voice":
                break;
            case "shortvideo":
                break;
            case "location":
                break;
            case "link":
                break;
            case "event":
                msg = dealEvent(requestMap);
                break;
            default:
                break;
        }
        //把消息对象处理为xml数据包
        return beanToXml(msg);
    }

    /**
     * 进行图片识别
     * @param requestMap
     * @return
     */
    private BaseMessage dealImage(Map<String, String> requestMap) {
        BdWordService bdWordService = new BdWordService();
        String result = "";
        //普通
//         result = bdWordService.generalBasic(requestMap);
        //高精度
//         result = bdWordService.accurate(requestMap);

        return new TextMessage(requestMap, result);
    }

    /**
     * 处理时间推送
     *
     * @param requestMap
     * @return
     */
    private BaseMessage dealEvent(Map<String, String> requestMap) {
        String event = requestMap.get("Event");
        switch (event) {
            case "CLICK":
                return dealClick(requestMap);
            case "VIEW":
                return dealView(requestMap);
            case "SCAN":
                return dealScan(requestMap);
            default:
                break;
        }
        return null;
    }


    /**
     * 处理click类型按钮的菜单
     * @param requestMap
     */
    private BaseMessage dealClick(Map<String, String> requestMap) {
        String key = requestMap.get("EventKey");
        switch (key) {
            case "12":
                //处理点击了1菜1
                return new TextMessage(requestMap, "你点击了1菜1");
            case "14":
                //处理点击了1菜2
                return new TextMessage(requestMap, "你点击了1菜2");
            case "22":
                //处理点击了2菜1
                return new TextMessage(requestMap, "你点击了2菜1");
            case "34":
                //处理点击了3菜2
                return new TextMessage(requestMap, "你点击了3菜2");
            default:
                break;
        }
        return null;
    }

    /**
     * 专门处理view类型的按钮的菜单
     * @param requestMap
     * @return
     */
    private BaseMessage dealView(Map<String, String> requestMap) {
        return null;
    }
    /**
     * 二维码扫描过来
     * @param requestMap
     * @return
     */
    private BaseMessage dealScan(Map<String, String> requestMap) {
        String resp ="公众号绑定成功!";
        User user = new User();
//        user.setGzhId(requestMap.get("ToUserName"));
        user.setGzhId(requestMap.get("FromUserName"));
        String userId = requestMap.get("EventKey");
        user.setUserId(Integer.valueOf(userId.substring(7,userId.length())));
        userService.updateGzhId(user);
        TextMessage tm = new TextMessage(requestMap, resp);
        return tm;
    }

    /**
     * 处理文本消息
     *
     * @param requestMap
     * @return
     */
    private BaseMessage dealTextMessage(Map<String, String> requestMap) {
        //用户发来的内容
        String msg = requestMap.get("Content");
        if (msg.equals("图文")) {
            List<Article> articles = new ArrayList<>();
            articles.add(new Article("甩手掌柜饼干", "好吃不贵",
                    "http://mmbiz.qpic.cn/mmbiz_jpg/Z4yATFldUsViaD5ibkQyw2Fadx8roT0fPs6utz1g2xfPEYyNZTFjZqCNicwmX8CGz4BNVIKRW0kt1BkBmDEVGlmuw/0",
                    "https://gzhsy.sszgjzx.com"));
            NewsMessage nm = new NewsMessage(requestMap, articles);
            return nm;
        }
//        String resp ="你好,甩手掌柜供应链";
        //调用方法返回聊天的内容
        String resp = chat(msg);

        TextMessage tm = new TextMessage(requestMap, resp);
        return tm;
    }

    /**
     * 把消息对象处理为xml数据包
     * @param msg
     * @return
     */
    private String beanToXml(BaseMessage msg) {
        XStream stream = new XStream();
        //设置需要处理XStreamAlias("xml")注解的类
        stream.processAnnotations(TextMessage.class);
        stream.processAnnotations(ImageMessage.class);
        stream.processAnnotations(MusicMessage.class);
        stream.processAnnotations(NewsMessage.class);
        stream.processAnnotations(VideoMessage.class);
        stream.processAnnotations(VoiceMessage.class);
        String xml = stream.toXML(msg);
        return xml;
    }

    /**
     * 调用图灵机器人聊天
     * https://www.juhe.cn/docs/api/id/112
     * @param msg
     * @return
     */
    private String chat(String msg) {
        try {
            Qingyunke qk = new Qingyunke();
            String result = qk.netChat(msg);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
